package com.example.tbag.healthcare.Activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;

import com.example.tbag.healthcare.Application.MyApplication;
import com.example.tbag.healthcare.R;
import com.example.tbag.healthcare.Util.DatabaseHelper;
import com.example.tbag.healthcare.Util.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by tbag on 2017/5/1.
 */

public class RegisterActivity extends AppCompatActivity {

    private DatabaseHelper helper;
    @BindView(R.id.edit1)
    EditText account;
    @BindView(R.id.edit2)
    EditText password;
    @BindView(R.id.edit3)
    EditText name;
    @BindView(R.id.edit4)
    EditText type;
    
    
    @OnClick(R.id.btn_back)
    public void back(){
        finish();
    }

    @OnClick(R.id.btn1)
    public void login(){
        if(account.getText().toString().trim().isEmpty()){
            ToastUtil.show(this,"账号不能为空");
            return;
        }
        if(password.getText().toString().trim().isEmpty()){
            ToastUtil.show(this,"密码不能为空");
            return;
        }
        if(name.getText().toString().trim().isEmpty()){
            ToastUtil.show(this,"姓名不能为空");
            return;
        }
        if(type.getText().toString().trim().isEmpty()){
            ToastUtil.show(this,"科室不能为空");
            return;
        }
        if(!query()){
            add();
        }
    }

    private boolean query() {
        Cursor c = helper.getReadableDatabase().query("doc",null,"user=?",
                new String[]{account.getText().toString()},null,null,null);
        if(c.moveToFirst()){
            ToastUtil.show(this,"账号重复，请更换账号");
            return true;
        }
        return false;
    }
    
    private void add(){
        ContentValues cv = new ContentValues();
        cv.put("user",account.getText().toString());
        cv.put("password",password.getText().toString());
        cv.put("name",name.getText().toString());
        cv.put("type",type.getText().toString());
        helper.getWritableDatabase().insert("doc",null,cv);
        MyApplication.name = name.getText().toString();
        MyApplication.type = type.getText().toString();
        setResult(0);
        finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        helper = new DatabaseHelper(this);
    }
}
